package com.ftqh.project.travel.controller;
import com.ftqh.project.travel.notes.entity.NoteImage;
import com.ftqh.project.travel.notes.service.NoteImageService;
import com.ftqh.project.travel.security.entity.User;
import com.ftqh.project.travel.security.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Optional;
import java.util.UUID;

/**
 * Created by Administrator on 2017/5/11.
 */
@RestController
@RequestMapping("noteimages")
public class NoteImageController {
    private static final Logger logger = LoggerFactory.getLogger(NoteImageController.class);
    // 文件上传后的路径
    @Value("${image.root.path}")
    private String imageRootPath;

    @Autowired
    NoteImageService noteImageService;
    @Autowired
    UserService userService;
    @GetMapping("{id}")
    public NoteImage findById(@PathVariable("id") Long id){
        Optional<NoteImage> noteImage = noteImageService.findById(id);
        if(noteImage.isPresent()){
            return noteImage.get();
        }
        return null;

    }
    @GetMapping("show/{id}")
    public void showImage(@PathVariable("id") Long id, HttpServletResponse response){
        // 设置页面不缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setDateHeader("Expires", 0);
        // 设置输出的内容的类型为JPEG/jpg/png等图像
        response.setContentType("image/*");

        Optional<NoteImage> noteImage = noteImageService.findById(id);

        noteImage.ifPresent(image->{
            // 通过IO输出流输出到img标签
            try {
                String fileRootPath = imageRootPath.lastIndexOf("/")==(imageRootPath.length()-1) ? imageRootPath.substring(0,imageRootPath.length()-1) : imageRootPath;
                File file = new File(fileRootPath + image.getUri());
                if(file.exists()) {
                    FileInputStream fileInputStream = new FileInputStream(file);
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(
                            fileInputStream);
                    byte[] b = new byte[bufferedInputStream.available()];
                    bufferedInputStream.read(b);
                    OutputStream outputStream = response.getOutputStream();
                    outputStream.write(b);
                    // 关闭输入流
                    bufferedInputStream.close();
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
    @PostMapping(value = "/upload")
    public NoteImage upload(@RequestParam("xdaTanFileImg") MultipartFile file) {
        NoteImage noteImage = new NoteImage();
        if (file.isEmpty()) {
            return noteImage;
        }
        //获取当前用户名
        String authorName = SecurityContextHolder.getContext().getAuthentication().getName();

        // 获取文件名
        String originalFileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + originalFileName);
        // 获取文件的后缀名
        String suffixName = originalFileName.substring(originalFileName.lastIndexOf("."));
        logger.info("上传的后缀名为：" + suffixName);
        // 解决中文问题，liunx下中文路径图片显示问题
        String fileName = UUID.randomUUID() + suffixName;
        String fileRootPath = imageRootPath.lastIndexOf("/")==(imageRootPath.length()-1) ? imageRootPath.substring(0,imageRootPath.length()-1) : imageRootPath;
        String filtAbsolutePath = "/"+ authorName + "/" +fileName;
        String filtPath = fileRootPath + filtAbsolutePath;
        File dest = new File(filtPath );
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
            Optional<User> user = userService.findByUsername(authorName);
            noteImage.setAuthorId(user.get().getId());
            noteImage.setAuthorName(authorName);
            noteImage.setName(originalFileName.substring(0,originalFileName.lastIndexOf(".")-1));
            noteImage.setSuffix(suffixName);
            noteImage.setSize(file.getSize());
            noteImage.setUri(filtAbsolutePath);
            noteImageService.save(noteImage);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return noteImage;
    }
}
